#pragma once

#include <iostream>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <stdlib.h>
#include <wchar.h>


class Util
{
private:
    static char dec2hex(short int c)
    {
        if (0 <= c && c <= 9)
        {
            return c + '0';
        }
        else if (10 <= c && c <= 15)
        {
            return c + 'A' - 10;
        }
        else
        {
            return -1;
        }
    }

    static int hex2dec(char c)
    {
        if ('0' <= c && c <= '9')
        {
            return c - '0';
        }
        else if ('a' <= c && c <= 'f')
        {
            return c - 'a' + 10;
        }
        else if ('A' <= c && c <= 'F')
        {
            return c - 'A' + 10;
        }
        else
        {
            return -1;
        }
    }

public:
    static size_t ReadLine(int sock, std::string &out)
    {
        char ch = 'a';
        while (ch != '\n')
        {
            ssize_t s = recv(sock, &ch, 1, 0);
            if (s > 0)
            {
                if (ch == '\r')
                {                                 // 将换行符(\n、\r、\r\n)统一为\n
                    recv(sock, &ch, 1, MSG_PEEK); // 不进行读取，仅仅看一下个字符
                    if (ch == '\n')
                    {
                        recv(sock, &ch, 1, 0);
                    }
                    else
                    {
                        ch = '\n';
                    }
                }
                out.push_back(ch);
            }
            else if (s == 0)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
        return out.size();
    }

    static bool CutString(const std::string &target, std::string &prev, std::string &back, const std::string sep)
    {
        size_t pos = target.find(sep);
        if (pos != std::string::npos)
        {
            prev = target.substr(0, pos);
            back = target.substr(pos + sep.size());

            return true;
        }
        return false;
    }

    // 解码url
    static void url_decode(std::string&url)
    {
        int i = 0;
        int len = url.length();
        int res_len = 0;
        std::string tmp; 
        for (i = 0; i < len; ++i)
        {
            char c = url[i];
            if (c != '%')
            {
                tmp.push_back(c);//不是中文字符
            }
            else
            {
                char c1 = url[++i];
                char c0 = url[++i];
                int num = 0;
                num = hex2dec(c1) * 16 + hex2dec(c0);
                tmp.push_back( num);
            }
        }
        url=tmp;
    }
};